package com.atguigu.srb.core.config;

import com.atguigu.srb.base.consts.SrbMqConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Base64;

@Configuration
@Slf4j
public class MqConfig {
    //配置生产者确认
    @Resource
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //消息是否达到交换机的回调
        rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack,
                                           @Nullable String cause)->{
            if(!ack){
                //消息未到达交换机
                log.error("消息未到达交换机:{}",cause);
            }
        });
        //消息未到达队列的回调
        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText,
                                          String exchange, String routingKey)->{
            //一个消息有 交换机、路由key、消息内容
            log.error("消息未到达队列: replyCode={} ,replyText={} , " +
                    "exchange={} , routingKey={}, message={}",replyCode,
                    // mq的消息可以是对象、集合、字符串：可以将字节数组转为base64的字符串传递
                    replyText,exchange,routingKey, new String(Base64.getEncoder().encode(message.getBody())));
        });
    }

    //配置交换机
    @Bean
    public Exchange smsExchange(){
        return ExchangeBuilder.topicExchange(SrbMqConst.SMS_EXCHANGE)
                    .ignoreDeclarationExceptions()
                    .durable(true)
                    .build();
    }
    @Bean
    public MessageConverter messageConverter(){
        //json字符串转换器
        return new Jackson2JsonMessageConverter();
    }
}
